package com.za.upgradeshield;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
//@ConditionalOnProperty(prefix = "shield", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(ShieldProperties.class)
public class ShieldAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(ShieldResponseBuilder.class)
    public ShieldResponseBuilder defaultShieldResponseBuilder(ShieldProperties properties) {
        return (request, path) -> {
            ShieldProperties.ShieldResponseConfig cfg = properties.getResponse();
            return Response.fail(cfg.getCode(), cfg.getMessage());
        };
    }

    @Bean
    public ShieldInterceptor shieldInterceptor(ShieldProperties properties, ShieldResponseBuilder responseBuilder) {
        return new ShieldInterceptor(properties, responseBuilder);
    }

    @Bean
    public WebMvcConfigurer shieldWebMvcConfigurer(ShieldInterceptor interceptor) {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(interceptor);
            }
        };
    }
}
